// pages/FollowId/FollowId.js
const db = wx.cloud.database()
const app = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
let imgPrefix = 'cloud://cloud1-5guctpb76a6efae2.636c-cloud1-5guctpb76a6efae2-1316724426/bg/'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nickname: "加载中...",
        signature: "加载中...",
        avatar: defaultAvatarUrl,
        userID:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('acceptDataFromOpenerPage', (data) => {
       
        let _openid = data.openid
        this.getInfo(_openid)
        this.getPost(_openid)
        this.getActivity(_openid)
      })
    },
    getInfo(_openid) {
        let that = this
        db.collection('userDB').where({
            _openid: _openid
        }).get({
            success: function(res) {
              console.log(res);
                let data = res.data[0]
                let nickname = data.nickname
                let avatar = data.avatar
                let signature = data.signature
                let userID = data._id
                let games = data.games
                
                if ( avatar.length == 0 )
                    avatar = defaultAvatarUrl
                if ( signature.length == 0 )
                    signature = nickname + "很有个性，个性签名什么都没写"
                that.setData({nickname,avatar,signature,userID})
                that.getBoardGame(games)
            },
            fail: function(res) {
                wx.showToast({
                    title: '当前网络不可用，请稍后重试！',
                    icon: 'none'
                })
            }
        })
    },
    getBoardGame(games){
        let that = this
        let bgIDArr = []
        for ( let i in games ) {
            bgIDArr.push(i)
        }
        db.collection("bgDB").where({
            _id: db.command.in(bgIDArr)
        }).get({
            success: function(res) {
                let boardgame = []
                for ( let i in res.data ) {
                    let bg = {}
                    bg["pic"] = res.data[i].pic
                    bg["name"] = res.data[i].name
                    bg["id"] = res.data[i]._id
                    boardgame.push(bg)
                }
                that.setData({boardgame})
            }
        })
    },
    getActivity(_openid) {
      let that = this
      db.collection('activityDB').where(db.command.or([
          {_openid: _openid},
          {[`people.${_openid}`]:db.command.exists(true)}
      ])).get({
          success: (res) => {
              let activityArr = res.data
              console.log(activityArr);
              that.setData({activityArr})
          }
      })
  },
    gotoMyActivity() {
        wx.navigateTo({
          url: '../MyActivity/MyActivity',
        })
    },
    gotoSetInfo() {
        let avatar = this.data.avatar
        let nickname = this.data.nickname
        let signature = this.data.signature
        wx.navigateTo({
            url: '../SetInfo/SetInfo',
            success: function(res) {
                res.eventChannel.emit('acceptDataFromOpenerPage',{avatar:avatar,nickname:nickname,signature:signature})
            }
        })
    },              
       
    getPost(_openid) {
      let that = this
      db.collection('articleDB').where({
        _openid: _openid
      }).get({
          success: (res) => {
              let post = res.data.reverse()
              console.log(post);
              this.setData({post})
              for (let i = 0; i < post.length; i++) {
                let like = post[i].like
                that.setData({
                  ['post[' + i + '].likeNumber']: Object.keys(like).length,
                  ['post[' + i + '].commentNumber']: post[i].comment.length
                })
                  db.collection('userDB').where({
                      _openid: post[i]["_openid"]
                  }).get({
                      success: (res) => {
                        console.log(res)
                          if ( res.data.length == 0 ) {
                              post[i]['nickname'] = "微信用户"
                              post[i]["avatar"] = defaultAvatarUrl
                          }
                          else {
                              post[i]["nickname"] = res.data[0].nickname
                              if ( res.data[0].avatar )
                                  post[i]["avatar"] = res.data[0].avatar
                              else
                                  post[i]["avatar"] = defaultAvatarUrl
                          }
                          that.setData({post})
                      }
                  })
              }
          }
      })
  },
  gotoJoinActivity(e) {
    console.log(e);
      let id = e.currentTarget.dataset.id
      console.log(id);
      wx.navigateTo({
        url: '../JoinActivity/JoinActivity',
        success: function(res) {
            res.eventChannel.emit('acceptDataFromOpenerPage',{
              id: id
            })
        },
        fail: function(res) {
            console.log(res);
        }
      })
  },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
    },
    gotoBoardGame(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../BoardGame/BoardGame',
            success: function(res) {
                res.eventChannel.emit('acceptDataFromOpenerPage',{id: id})
            }
        })
    },
    gotoMyFavourite(e) {
        wx.navigateTo({
            url: '../MyFavourite/MyFavourite',
        })
    },
    gotoMyFollow(e) {
        wx.navigateTo({
          url: '../MyFollow/MyFollow',
        })
    },
    gotoArticle(e){
      console.log(e);
      let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../Article/Article',
            success: function(res) {
              res.eventChannel.emit('acceptDataFromOpenerPage',{id: id})
          }
        })
    },
    deleteActivity(e) {
        let id = e.currentTarget.dataset.id
        wx.showModal({
            title: '你真的要删除这个活动吗？',
            content: '不能跟小伙伴愉快的玩耍了！',
            confirmText: '删除',
            confirmColor: 'red',
            cancelColor: '#ccc',
            success: res => {
                if (res.confirm) {
                    wx.showLoading({
                      title: '删除中...',
                    })
                    db.collection('activityDB').doc(id).remove({
                        success: res => {
                            db.collection('activityDB').where({
                                _openid: app.globalData.openid
                            }).get({
                                success: res => {
                                    wx.showToast({
                                        title: '删除成功！',
                                    })
                                    let activityArr = res.data
                                    console.log(activityArr);
                                    this.setData({activityArr})
                                }
                            })
                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    deleteArticle(e) {
        let that = this
        let id = e.currentTarget.dataset.id
        wx.showModal({
            title: '你真的要删除这个帖子吗？',
            content: '不能跟小伙伴愉快的讨论了！',
            confirmText: '删除',
            confirmColor: 'red',
            cancelColor: '#ccc',
            success: res => {
                if (res.confirm) {
                    wx.showLoading({
                      title: '删除中...',
                    })
                    db.collection('articleDB').doc(id).remove({
                        success: res => {
                            db.collection('articleDB').where({
                                _openid: app.globalData.openid
                            }).get({
                                success: res => {
                                    wx.showToast({
                                        title: '删除成功！',
                                    })
                                    let post = res.data
                                    this.setData({post})
                                    for (let i = 0; i < post.length; i++) {
                                        db.collection('userDB').where({
                                            _openid: post[i]["_openid"]
                                        }).get({
                                            success: (res) => {
                                              console.log(res)
                                                if ( res.data.length == 0 ) {
                                                    post[i]['nickname'] = "微信用户"
                                                    post[i]["avatar"] = defaultAvatarUrl
                                                }
                                                else {
                                                    post[i]["nickname"] = res.data[0].nickname
                                                    if ( res.data[0].avatar )
                                                        post[i]["avatar"] = res.data[0].avatar
                                                    else
                                                        post[i]["avatar"] = defaultAvatarUrl
                                                }
                                                that.setData({post})
                                            }
                                        })
                                    }
                                }
                            })
                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.getInfo()
        this.getActivity()
        this.getBoardGame()
        setTimeout(function(){
            wx.stopPullDownRefresh();
        },300);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})